﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using System.Text.RegularExpressions;
using ZeroBug.EasyFlow.Core;

namespace EasyFlow
{
    public partial class VariableExpressionViewModel : ObservableObject
    {
        private readonly VariableExpression variableExpression;
        private VariableTreeView _variableTreeView;
        public string VarExpName => this.variableExpression.VarExpName;
        private string _varExp;
        public string VarExp
        {
            get => _varExp;
            set
            {
                SetProperty<string>(ref _varExp, value);
                variableExpression.Expressions = value.Split(',').ToList();
            }
        }
        
        public VariableExpressionViewModel(VariableExpression expressionVariable)
        {
            this.variableExpression = expressionVariable;
            this._varExp = string.Join(',', expressionVariable.Expressions);
        }
        [RelayCommand]
        void VariableLinkButtonClick()
        {
            if (_variableTreeView != null && _variableTreeView.IsInitialized && _variableTreeView.IsVisible)
            {
                if (_variableTreeView.WindowState == System.Windows.WindowState.Minimized)
                    _variableTreeView.WindowState = System.Windows.WindowState.Normal;
                _variableTreeView.Activate();
            }
            else
            {
                _variableTreeView = new VariableTreeView();
                _variableTreeView.DataContext = new VariableManagerViewModel(App.Current.Services.GetService<FlowManager>());
                _variableTreeView.AppendVariableCommand = AppendVariableCommand;
                _variableTreeView.ReplaceVariableCommand = ReplaceVariableCommand;
                _variableTreeView.Show();
            }
        }
        [RelayCommand]
        void AppendVariable(object obj)
        {
            if (obj is VariableViewModel)
            {
                VariableViewModel vvm = obj as VariableViewModel;
                if (!string.IsNullOrEmpty(VarExp))
                    VarExp += $",@[{vvm.BindingVariable.Name}]";
                this.variableExpression.Expressions = VarExp.Split(',').ToList();
            }
        }
        [RelayCommand]
        void ReplaceVariable(object obj)
        {
            if (obj is VariableViewModel)
            {
                VariableViewModel vvm = obj as VariableViewModel;
                VarExp = $"@[{vvm.BindingVariable.Name}]";
                this.variableExpression.Expressions = new List<string>() { VarExp };
                //if (!vvm.IsNodeOnly)
                //{
                //    (_variableTreeView.DataContext as VariableManagerViewModel).SelectedVariableName = vvm.Name;
                //    //VarExp = vvm.Name;
                //}
            }
        }
    }
}
